package zzjson.rabbitmq.simple;

import com.rabbitmq.client.*;
import zzjson.rabbitmq.constants.RabbitConstants;
import zzjson.rabbitmq.constants.RabbitExchange;
import zzjson.rabbitmq.constants.RabbitQueueConstans;
import zzjson.rabbitmq.constants.RabbitRoutingKey;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;


/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.rabbitmq.simple</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年04月25日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class MyConsumer {
	/**
	 * @param args
	 * @throws IOException
	 * @throws TimeoutException
	 */
	public static void main(String[] args) throws IOException, TimeoutException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUsername(RabbitConstants.UserName);
		factory.setPassword(RabbitConstants.password);
		factory.setVirtualHost("/");
		factory.setHost(RabbitConstants.host);

		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();

		//声明交换机
		channel.exchangeDeclare(RabbitExchange.SIMPLE_EXCHANGE, BuiltinExchangeType.DIRECT, false, false, null);

		//声明队列 exclusive :排他性，只对当前连接可见
		channel.queueDeclare(RabbitQueueConstans.SIMPE_QUEUENAME, false, true, false, null);
		System.out.println("wait for message ........");

		channel.queueBind(RabbitQueueConstans.SIMPE_QUEUENAME,
				RabbitExchange.SIMPLE_EXCHANGE, RabbitRoutingKey.SIMPLEKEY);

		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
				// super.handleDelivery(consumerTag, envelope, properties, body);
				String msg = new String(body, StandardCharsets.UTF_8);
				System.out.println("Received message : '" + msg + "'");
				System.out.println("consumerTag : " + consumerTag);
				System.out.println("deliveryTag : " + envelope.getDeliveryTag());
			}
		};

		// 开始获取消息
		// String queue, boolean autoAck, Consumer callback
		channel.basicConsume(RabbitQueueConstans.SIMPE_QUEUENAME, true, consumer);
	}
}